package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import com.example.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法运行前运行，返回true，放行，返回false，不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url。
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}",url);
        //2.判断url中是否包含login，如果包含，说明是登录请求，放行
        if (url.contains("login") || url.contains("register")  ||
                url.contains("article/selectall") ||
                url.contains("article/mlist") ||
                url.contains("article/detail") ||
                url.contains("article/listAll") ||
                url.contains("article/addViewCount") ||
                url.contains("category/list") ||
                url.contains("code") ||
                url.contains("feedback") ||
                url.contains("competition/listCategory") ||
                url.contains("article/search_suggest")
        ){

            log.info("无需登录操作，放行...");
            return true;
        }
        //3.获取请求头中的令牌（token）
        String jwt = request.getHeader("token");

        //打断一下
        if ((url.contains("article/detail") && jwt == null)){
            return true;
        }


        //4.是否存在
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为空，返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换json格式
            String noLogin = JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return false;
        }
        //5.存在则解析
        try {
           Claims claims = JwtUtils.parseJWT(jwt);
           ThreadLocalUtil.set(claims);
        } catch (Exception e){//解析失败
            e.printStackTrace();
            log.info("解析令牌失败 返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换json格式
            String noLogin = JSONObject.toJSONString(error);
            response.getWriter().write(noLogin);
            return false;
        }
        //6.放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override//目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override//视图渲染完毕后运行,最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
        // 清除线程变量
        log.info("清理线程变量");
        ThreadLocalUtil.remove();
    }
}
